package com.jiuqi.jjintfp.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiuqi.jjintfp.enumeration.ResultEnum;
import com.jiuqi.jjintfp.mapper.EnICInfoMapper;
import com.jiuqi.jjintfp.model.EnterpriseICInfo;
import com.jiuqi.jjintfp.model.Result;
import com.jiuqi.jjintfp.model.AppAuthMapping;
import com.jiuqi.jjintfp.service.ICInfoService;
import com.jiuqi.jjintfp.util.CommonUtils;
import com.jiuqi.jjintfp.util.RequestUtil;

@Service("ICInfoService")
public class ICInfoServiceImpl implements ICInfoService {
	
	private Logger logger = Logger.getLogger(ICInfoServiceImpl.class);
	
	@Resource
	private EnICInfoMapper enICInfoMapper;
	
	@Autowired
	private AsyncInsertTask insertTask;
	
	@Autowired
	private AppAuthMapping authMapping;
	
	private final String[] array = {"KeyNo", "Name", "No", "BelongOrg", "OperName", "StartDate", "EndDate", "Status", "Province", 
			"UpdatedDate", "CreditCode", "RegistCapi", "EconKind", "Address", "Scope", "TermStart", "TeamEnd", "CheckDate", 
			"OrgNo", "IsOnStock", "StockNumber", "StockType"};

	@Override
	public Result<EnterpriseICInfo> getICInfo(String requestIp, String unit, String key, String keyword) {
		Result<EnterpriseICInfo> result = new Result<>();
		Map<String, String> unitKeyMap = authMapping.getMapProps();
		if (!unitKeyMap.containsKey(unit) || (unitKeyMap.containsKey(unit) && !unitKeyMap.get(unit).toString().equals(key))) {
			result.setStatus(ResultEnum.NO_AUTH.getCode());
			result.setMessage(ResultEnum.NO_AUTH.getMsg());
			return result;
		}
		Map<String, String> param = new LinkedHashMap<String, String>();
		param.put(CommonUtils.REQ_KEY, authMapping.getAppKey());
		param.put(CommonUtils.REQ_KEYWORD, keyword);
		EnterpriseICInfo enICInfo = null;
		try {
			keyword = URLDecoder.decode(keyword, "UTF-8");
			enICInfo = enICInfoMapper.queryEnICInfoByName(keyword);
			if (enICInfo == null) {
				enICInfo = enICInfoMapper.queryEnICInfoByNo(keyword);
				if (enICInfo == null) {
					enICInfo = enICInfoMapper.queryEnICInfoByCode(keyword);
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("keyword解码异常:" + keyword, e);
			result.setStatus(ResultEnum.DECODE_EXCP.getCode());
			result.setMessage(ResultEnum.DECODE_EXCP.getMsg());
			return result;
		} catch (Exception e) {
			logger.error("mysql数据库异常", e);
			result.setStatus(ResultEnum.DB_EXCP.getCode());
			result.setMessage(ResultEnum.DB_EXCP.getMsg());
			return result;
		}
		if (enICInfo != null) {
			result.setStatus(ResultEnum.QUERY_SUCCESS.getCode());
			result.setMessage(ResultEnum.QUERY_SUCCESS.getMsg());
			result.setResult(enICInfo);
			logger.info("ip:" + requestIp + ",查询企业工商信息成功");
			return result;
		}
		String rtnStr = RequestUtil.doGet(authMapping.getAddress(), param);
		if (!"".equals(rtnStr)) {//""为异常
			JSONObject jsonObject = JSON.parseObject(rtnStr); 
			if (!("200").equals(jsonObject.get("Status"))) {
				logger.info("ip:" + requestIp + ",没有查询到企业工商信息");
				result.setStatus(ResultEnum.NO_RESULT.getCode());
				result.setMessage(ResultEnum.NO_RESULT.getMsg());
				return result;//{"Status":"201","Message":"查询无结果","OrderNumber":null,"Result":null}
			}
			String r = jsonObject.get("Result").toString();
			JSONObject resultJson = JSON.parseObject(r);
			EnterpriseICInfo icInfo = JSON.parseObject(resultJson.toJSONString(), EnterpriseICInfo.class);
			for (int i = 0; i < array.length; i ++) {
				resultJson.remove(array[i]);
			}
			icInfo.setOther(resultJson.toJSONString());
			insertTask.insertEnICInfo(icInfo);
			logger.info("ip:" + requestIp + ",查询企业工商信息成功");
			result.setStatus(ResultEnum.QUERY_SUCCESS.getCode());
			result.setMessage(ResultEnum.QUERY_SUCCESS.getMsg());
			result.setResult(icInfo);
			return result;
		}
		result.setStatus(ResultEnum.CALL_QCC_EXCP.getCode());
		result.setMessage(ResultEnum.CALL_QCC_EXCP.getMsg());
		return result;
	}
}
